package by.yativem.commons.utils.math;

import java.lang.reflect.Array;
import java.util.Arrays;

import org.apache.log4j.Logger;

public class Utils {
	private static final Logger log = Logger.getLogger(Utils.class);

	private Utils(){
		
	}
	
	
	public static Byte[] convertToBitRepresent(long o) {
		long lo = o;
		Double d = Math.log(lo) / Math.log(2);
		int index = (int) Math.round(d + 0.5D);
		Byte[] result = new Byte[Long.SIZE];
		if (lo < 0) {
			result[0] = 1;
		} else {
			result[0] = 0;
		}

		for (int i = 1; i < Long.SIZE - index; i++) {
			result[i] = 0;
		}

		index = Long.SIZE - index;
		while (lo > 0) {
			if (lo % 2 == 1) {
				result[index] = 0;
			} else {
				result[index] = 1;
			}
			index++;
			lo = lo / 2;
		}

		return result;
	}

	public static Byte[] convertToBitRepresent(long o, int arrSize) throws Exception {
		Byte[] result  = null;
		try {
			
		
		long lo = o;
		Double d = Math.log(lo) / Math.log(2);
		int index = (int) Math.round(d + 0.5D);
		if (arrSize - 1 < index) {
			throw new Exception("The value is bigger");
		}
	 result = new Byte[arrSize];
		if (lo < 0) {
			result[0] = 1;
		} else {
			result[0] = 0;
		}

		for (int i = 1; i < arrSize - index ; i++) {
			result[i] = 0;
		}

		index = arrSize- index;
		while (lo > 0) {
			if (lo % 2 == 1) {
				result[index] = 0;
			} else {
				result[index] = 1;
			}
			index++;
			lo = lo / 2;
		}
		} catch (Exception e) {
			log.error("", e);
			throw e;
		}

		return result;
	}
	
	public static Double[] convertByteToDouble(Byte[] array){
		Double[] result = new Double[array.length];
		int i = 0; 
		for(Byte b : array){
			result[i] = b.doubleValue();
			i++;
		}
		
		return result;
	}

	public static String byteArrayToString(Byte[] b) {
		StringBuilder sb = new StringBuilder();
		for (Byte bb : b) {
			sb.append(bb);
		}
		return sb.toString();
	}
	
	public static Byte[] concat(Byte[] b1 ,Byte[] b2 ){
		Byte[] r = new Byte[b1.length + b2.length ];
		int i = 0;
		for(Byte b :b1 ){
			r[i] = b;
			i++;
		}
		for(Byte b :b2 ){
			r[i] = b;
			i++;
		}
		
		return r;
	}

	public static void main(String[] arg) {
		DoubleMath dm = new DoubleMath();

		Byte[] t1 = dm.convertToBitRepresent(12D);
		System.out.println(12D);
		System.out.println(DoubleMath.byteArrayToString(t1));
	}
}
